package com.lagou.handler;

import com.lagou.request.RpcRequest;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 自定义的业务处理器
 */
@Component
@ChannelHandler.Sharable
public class ServiceHandler extends ChannelInboundHandlerAdapter {
    @Autowired
    private ApplicationContext applicationContext;

    //当客户端读取数据时,该方法会被调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof RpcRequest) {
            RpcRequest request = (RpcRequest) msg;
            //获取调用的Service对象
            String className = request.getClassName();

            Object service = applicationContext.getBean(className);
            //获取调用的方法
            Method method = service.getClass().getMethod(request.getMethodName(), request.getParameterTypes());
            //执行
            Object retResult = method.invoke(service, request.getParameters());

            //3.把调用实现类的方法获得的结果写到客户端
            ctx.writeAndFlush(retResult);
        }
    }
}
